<template>
  <div>
    <div v-if="mounted">
      <FormRender
        ref="formRenderRef"
        v-model:config="formJson"
        v-model="formData"
        :mode="props.mode"
        :perm="formPerm"
      />
    </div>
    <footer class="el-dialog__footer">
      <span class="dialog-footer">
        <el-button
          v-if="props.dialog"
          type="warning"
          @click="close"
          icon="Close"
          >关闭</el-button
        >
        <el-button
          v-if="!props.readonly && props.mode != 'read' && data.orderInst.id"
          v-loading="loading"
          type="primary"
          @click="saveForm"
          :disabled="loading"
          icon="circle-check"
          >保存</el-button
        >
      </span>
    </footer>
  </div>
</template>

<script setup lang="ts" name="OrderFlowForm">
import { getObj, updateFormData } from "@/api/flow/orderinst";
import { parseWithFunctions } from "@/utils/process";
import { reactive, ref } from "vue";
import { useMessage } from "@/hooks/message";
import { cloneObject } from "@/utils/common";
import { validateNull } from "@/utils/validate";
import { queryList } from "@/api/flow/formperm";
import FormRender from "@/views/design/form/FormRender.vue";

const emits = defineEmits(["close", "saved"]);

const props = defineProps({
  //表单模式，free设计模式，normal 编辑模式, read 阅读模式，disable 禁用模式
  mode: {
    type: String,
    default: "normal"
  },
  defNodeId: {
    type: String,
    default: ""
  },
  orderInstId: {
    type: String,
    default: ""
  },
  dialog: {
    type: Boolean,
    default: false
  },
  readonly: {
    type: Boolean,
    default: true
  }
});

const formRenderRef = ref(null);
const loading = ref(false);
const formData = ref({});
const formPerm = ref([]);
const mounted = ref(false);
const tableListRefs = ref<any>({});
const componentRefs = ref<any>({});
provide("componentRefs", componentRefs);
provide("tableListRefs", tableListRefs);

const data = reactive({
  submitBtn: true,
  form: {
    id: "",
    formName: "",
    formRemark: "",
    formStatus: "0",
    formTypeId: "",
    formTypeCode: "",
    formTypeName: "",
    formInfo: "",
    printInfo: ""
  },
  orderInst: {
    id: "",
    defFlowId: "",
    formId: "",
    flowInstId: ""
  }
});

const formJson = computed(() => {
  if (data.form && data.form.formInfo) {
    let formInfo = parseWithFunctions(data.form.formInfo);
    return formInfo;
  } else {
    return {
      conf: {
        labelPosition: "right", //标签位置
        labelWidth: 80, //标签宽度，
        size: "default"
      },
      components: []
    };
  }
});

const disableForm = () => {
  nextTick(() => {
    formRenderRef.value.disableForm();
  });
};

const enableForm = () => {
  nextTick(() => {
    formRenderRef.value.enableForm();
  });
};

//办理时传入orderInstId
const initOrderInstById = async id => {
  getObj(id).then(res => {
    if (res.code === 200) {
      data.orderInst.id = res.data.id;
      data.orderInst.defFlowId = res.data.defFlowId;
      data.orderInst.formId = res.data.formId;
      data.orderInst.flowInstId = res.data.flowInstId;
      if (res.data.flowForm) {
        const flowForm = parseWithFunctions(res.data.flowForm);
        cloneObject(data.form, flowForm);
        let formInfo = parseWithFunctions(data.form.formInfo);
        if (!formInfo.conf || !formInfo.components) {
          useMessage().error("表单配置错误");
          return;
        }
      }
      if (res.data.formData) {
        const data = parseWithFunctions(res.data.formData);
        formData.value = data;
      }
    }
    if (props.defNodeId) {
      queryList({ defNodeId: props.defNodeId }).then(res => {
        if (res.code === 200) {
          formPerm.value = res.data;
        }
        mounted.value = true;
        if (props.readonly) {
          disableForm();
        } else {
          enableForm();
        }
      });
    } else {
      mounted.value = true;
      if (props.readonly) {
        disableForm();
      } else {
        enableForm();
      }
    }
  });
};

const saveForm = async () => {
  try {
    loading.value = true;
    let formData = await formRenderRef.value.getFormData();
    if (validateNull(formData)) {
      useMessage().warning("请输入表单信息");
      return;
    }
    const params = {
      orderInstId: data.orderInst.id,
      flowInstId: data.orderInst.flowInstId,
      formId: data.orderInst.formId,
      formData: JSON.stringify(formData)
    };
    updateFormData(params).then(res => {
      if (res.code === 200) {
        useMessage().success("表单数据保存成功");
        emits("saved");
      } else {
        useMessage().error(res.msg);
      }
    });
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};

const close = () => {
  emits("close");
};

watchEffect(() => {
  if (props.orderInstId) {
    initOrderInstById(props.orderInstId);
  }
});
</script>

<style lang="scss" scoped>
.el-dialog__footer {
  padding-top: 8px 0px !important;
  text-align: center;

  .dialog-footer {
    text-align: center;
  }
}
</style>
